package com.yunbiao.ybbusstopplate.ui.usbserver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import com.yunbiao.ybbusstopplate.utils.eventbus.UsbEvent;
import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class UsbReceiver extends BroadcastReceiver {

    private static final String TAG = "UsbReceiver";

    private final Context context;

    public UsbReceiver(Context context) {
        this.context = context;

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_SHARED); // 如果SDCard未安装,并通过USB大容量存储共享返回
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED); // 表明sd对象是存在并具有读/写权限
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); // SDCard已卸掉,如果SDCard是存在但没有被安装
        filter.addAction(Intent.ACTION_MEDIA_CHECKING); // 表明对象正在磁盘检查
        filter.addAction(Intent.ACTION_MEDIA_EJECT); // 物理的拔出 SDCARD
        filter.addAction(Intent.ACTION_MEDIA_REMOVED); // 完全拔出
        filter.addDataScheme("file"); // 必须要有此行，否则无法收到广播
        context.registerReceiver(this,filter);
    }

    public void unregister(){
        this.context.unregisterReceiver(this);
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(intent.ACTION_MEDIA_MOUNTED)) {//具有可读写的sd卡
            Log.e(TAG, " U盘被插入----------------" );
            String usbPath = intent.getData().getPath();
            //将U盘路径临时储存至本地
            //注：有的U盘路径和打印显示的不一致，暂未解决，可更换U盘解决
            Log.d(TAG, "onReceive: usbPath----->"+usbPath);
            if (!TextUtils.isEmpty(usbPath)){
                EventBus.getDefault().post(new UsbEvent());
            }

        }else if (intent.getAction().equals(intent.ACTION_MEDIA_UNMOUNTED)){
            Log.e(TAG, " U盘被拔出----------------" );
            String usbPath = intent.getData().getPath();
            //将U盘路径临时储存至本地
            //注：有的U盘路径和打印显示的不一致，暂未解决，可更换U盘解决
            Log.d(TAG, "onReceive: usbPath----->"+usbPath);
            if (!TextUtils.isEmpty(usbPath)){
                EventBus.getDefault().post(new UsbEvent());
            }
        }
    }




}